<template>
  <confirm-bar :visible="downloadBarVisible">
    <template #content>
      已选&nbsp;{{ selectedRowKeys.length }}&nbsp;项
    </template>
    <template #handle>
      <a-button type="link" @click="onCancel">取消选择</a-button>
      <a-button
        type="link"
        @click="onConfirm"
        :loading="loading"
        :disabled="selectedRowKeys.length === 0"
      >
        下载
      </a-button>
    </template>
  </confirm-bar>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import ConfirmBar from '@/components/confirm-bar/confirm-bar.vue'
import {
  useRowSelectionActive,
  useRowSelection,
  useLockForInUse,
  useDownloadBarVisible,
  useTreeSelectedInfo,
  useDataSourceManager,
} from './provide-context.js'
import { downloadFile, flushDataStatus } from '@/api/db.js'
import { downloadFormBlob } from '@/utils/util.js'
import { useDbType } from './provide-context.js'
/**
 * 全局
 */
let rowSelectionActive = useRowSelectionActive()
let rowSelection = useRowSelection()
let { selectedRowKeys } = rowSelection
let lockForInUse = useLockForInUse()
let downloadBarVisible = useDownloadBarVisible()
let treeSelectedInfo = useTreeSelectedInfo()
let { update } = useDataSourceManager()
/**
 * 操作逻辑
 */
let loading = ref(false)
function onCancel() {
  downloadBarVisible.value = false
  rowSelectionActive.value = false
  lockForInUse.value = null
  delete rowSelection.getCheckboxProps
}

if (treeSelectedInfo) {
  watch(treeSelectedInfo, onCancel)
}

let dbType = useDbType()
async function onConfirm() {
  loading.value = true
  let timer = setTimeout(() => {
    update()
  }, 1000)
  try {
    await Promise.all(
      selectedRowKeys.value.map(id => {
        return downloadFile({ id }, dbType)
          .then(downloadFormBlob)
          .catch(() => {
            message.error(`下载失败<${id}>`)
          })
      }),
    )

    await Promise.all(
      selectedRowKeys.value.map(async id => {
        await flushDataStatus({ id })
      }),
    )

    downloadBarVisible.value = false
    rowSelectionActive.value = false
    lockForInUse.value = null
    delete rowSelection.getCheckboxProps
  } catch (e) {}
  loading.value = false
  clearTimeout(timer)
  update()
}
</script>
